using Microsoft.AspNetCore.Mvc;
using B.S.Medical.Api.Write.Services.Pay;
using System.Threading.Tasks;
using B.S.Medical.ErrorCode;
using System;
using MediatR;
using B.S.Medical.Api.Write.Application.Command.Pay;
using B.S.Medical.Domain.Payment;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Infrastructure.Interface;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace B.S.Medical.Api.Write.Controllers.Pay
{
    /// <summary>
    /// 充值控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class PayController : ControllerBase
    {
        private readonly IAlipayService _alipayService;
        private readonly IMediator _mediator;
        private readonly IBaseRepository<PaymentRecordModel> _paymentRepository;
        private readonly IBaseRepository<PatientBalance> _patientBalanceRepository;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public PayController(
            IAlipayService alipayService, 
            IMediator mediator,
            IBaseRepository<PaymentRecordModel> paymentRepository,
            IBaseRepository<PatientBalance> patientBalanceRepository)
        {
            _alipayService = alipayService;
            _mediator = mediator;
            _paymentRepository = paymentRepository;
            _patientBalanceRepository = patientBalanceRepository;
        }

        /// <summary>
        /// 患者余额充值（手机网站支付）
        /// </summary>
        /// <param name="model">充值模型</param>
        /// <returns>跳转到支付宝支付页面</returns>
        /// <remarks>
        /// 创建余额充值订单，使用支付宝手机网站支付
        /// </remarks>
        [HttpPost]
        public Task<ApiResult<PaymentRecordModel>> RechargeBalance([FromBody] RechargeBalanceModel model)
        {
                var res=new ApiResult<PaymentRecordModel>();
                // 生成订单号
                string orderNo = $"RCH{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999)}";
                
                // 1. 创建支付记录
                var paymentRecord = new PaymentRecordModel
                {
                    OrderNo = orderNo,
                    PatientId = model.PatientId,
                    DoctorId = 0, // 充值不需要医生ID，填0
                    ItemName = "余额充值",
                    Amount = model.Amount,
                    PayAmount = model.Amount,
                    IsPaid = false,
                    PayType = "支付宝",
                    PayChannel = "手机网站支付",
                    PayStatus = "待支付",
                    CreatedTime = DateTime.Now,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };
                
                var r= _paymentRepository.CreateAsync(paymentRecord).Result;
                if (r > 0)
                {
                    res.Code = ApiEnum.Success;
                    res.Message = "余额充值生成订单号成功";
                    res.Data = paymentRecord;
                }
                else
                {
                    res.Code = ApiEnum.Fail;
                    res.Message = "余额充值生成订单号失败";
                    res.Data = paymentRecord;
                }
                return Task.FromResult(res);

                
                //// 2. 构造支付请求模型
                //var payViewModel = new AlipayTradeWapPayViewModel
                //{
                //    OutTradeNo = orderNo,
                //    Subject = "余额充值",
                //    Body = $"患者ID: {model.PatientId} 余额充值",
                //    TotalAmount = model.Amount.ToString("0.00"),
                //    NotifyUrl = "http://101.201.170.32:5289/api/AlipayNotify/wappay",
                //    ReturnUrl = string.IsNullOrEmpty(model.ReturnUrl) ? "http://localhost:5173/recharge/success" : model.ReturnUrl
                //};
                
                //// 3. 转发到AlipayController.WapPay方法
                //return RedirectToAction("WapPay", "Alipay", payViewModel);
            }
        }

        ///// <summary>
        ///// 根据患者Id充值余额
        ///// </summary>
        ///// <param name="patientId">患者ID</param>
        ///// <param name="addBalance">要充值的余额</param>
        ///// <returns>操作结果</returns>
        //[HttpPost]
        //public async Task<ApiResult<bool>> AddToPatientBalance(int patientId, decimal addBalance)
        //{
        //    try
        //    {
        //        var patientBalance = await _patientBalanceRepository.GetAll()
        //            .FirstOrDefaultAsync(b => b.PatientId == patientId && !b.IsDeleted);
        //        if (patientBalance == null)
        //        {
        //            return new ApiResult<bool>
        //            {
        //                Code = ApiEnum.Fail,
        //                Msg = "该患者余额记录不存在，无法累加！",
        //                Data = false
        //            };
        //        }
        //        patientBalance.Balance += addBalance;
        //        patientBalance.UpdateTime = DateTime.Now;
        //        patientBalance.LastUpdatedTime = DateTime.Now;
        //        patientBalance.Remark = $"充值 {addBalance} 元";
        //        await _patientBalanceRepository.UpdateAsync(patientBalance);
        //        return new ApiResult<bool>
        //        {
        //            Code = ApiEnum.Success,
        //            Msg = "余额充值成功",
        //            Data = true
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult<bool>
        //        {
        //            Code = ApiEnum.Error,
        //            Msg = $"余额充值失败: {ex.Message}",
        //            Data = false
        //        };
        //    }
        //}

        ///// <summary>
        ///// 支付宝退款
        ///// </summary>
        ///// <param name="dto">退款信息</param>
        ///// <returns>退款结果</returns>
        ///// <remarks>
        ///// 申请支付宝退款，更新订单状态和患者余额
        ///// </remarks>
        //[HttpPost]
        //public async Task<ApiResult<bool>> AlipayRefund([FromBody] RefundPayOrderDto dto)
        //{
        //    try
        //    {
        //        var success = await _alipayService.RefundAsync(dto);
                
        //        return new ApiResult<bool>
        //        {
        //            Code = ApiEnum.Success,
        //            Msg = "退款成功",
        //            Data = success
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult<bool>
        //        {
        //            Code = ApiEnum.Error,
        //            Msg = $"退款失败: {ex.Message}",
        //            Data = false
        //        };
        //    }
        //}

        ///// <summary>
        ///// 更新支付订单状态
        ///// </summary>
        ///// <param name="command">更新支付状态命令</param>
        ///// <returns>更新结果</returns>
        ///// <remarks>
        ///// 手动更新支付订单的状态，包括支付状态、是否已支付、支付时间等信息
        ///// </remarks>
        //[HttpPost("UpdatePaymentStatus")]
        //public async Task<ApiResult<bool>> UpdatePaymentStatus([FromBody] Application.Command.Pay.UpdatePaymentStatusCommand command)
        //{
        //    try
        //    {
        //        return await _mediator.Send(command);
        //    }
        //    catch (Exception ex)
        //    {
        //        return new ApiResult<bool>
        //        {
        //            Code = ApiEnum.Error,
        //            Msg = $"更新订单状态失败: {ex.Message}",
        //            Data = false
        //        };
        //    }
        //}
    

    /// <summary>
    /// 余额充值模型
    /// </summary>
    public class RechargeBalanceModel
    {
        /// <summary>
        /// 患者ID
        /// </summary>
        public int PatientId { get; set; }

        /// <summary>
        /// 充值金额
        /// </summary>
        public decimal Amount { get; set; }
    }
} 